package com.gitee.huxing.course.conc.conc02.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc02.lock
 * @ClassName: ReentrantReadWriteLockDemo2
 * @Author: huxing
 * @DateTime: 2021-08-25 上午11:22
 */
public class ReentrantReadWriteLockDemo2 {

    private final Map<String, Object> map = new HashMap<>();

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public Object readwrite(String key){
        Object value = null;
        System.out.println("1. 首先开启读锁");
        lock.readLock().lock();
        try {
            value = map.get(key);
            if (value == null){
                System.out.println("2. 数据不存在，开启写锁");
                lock.readLock().unlock();
                lock.writeLock().lock();
                try {
                    if (value == null){
                        value = "aaaa";
                    }
                } finally {
                    System.out.println("3. 释放写锁");
                    lock.writeLock().unlock();
                }
                System.out.println("4. 开启读锁");
                lock.readLock().lock();
            }
        }finally {
            System.out.println("5. 释放读锁");
            lock.readLock().unlock();
        }
        return value;
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockDemo2 demo2 = new ReentrantReadWriteLockDemo2();
        demo2.readwrite("bingfabiancheng ");
    }
}
